import React, { useState, useEffect, useMemo } from "react";
import shopcart from "../style/shopcart.module.css";
import { useNavigate } from "react-router-dom";
import navIcon1 from "../img/ones.png";
import navIcon2 from "../img/fours.png";
import navIcon3 from "../img/10019.png";
import navIcon4 from "../img/two.png";
import navIcon5 from "../img/threes.png";
import Jian from "../img/jian.png";
import Jia from "../img/add.png";
import { shopping, shopping_del } from "../api/shopping"; //购物车接口封装
import { home } from "../api/home";
interface CartItem {
  id: string;
  goods_id: string; // 确保 goods_id 存在
  num: number | string;
  price: number | string;
  title: string;
  norm: string;
  img: string;
  checked: boolean;
}

interface Product {
  id: number;
  title?: string;
  synopsis?: string;
  price: number | string;
  original_price?: number | string;
  img?: string;
}

interface ApiResponse {
  data?: {
    list?: Product[];
    // list?: any[]; // 根据实际API调整
  };
}

const ShopCart = () => {
  const navigate = useNavigate();
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [shopList, setShopList] = useState<Product[]>([]);
  const [allChecked, setAllChecked] = useState(false);
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");
  // 数据初始化时确保 num、price 是数字，并确保 goods_id 存在
  const normalizeCartItem = (item: any): CartItem => ({
    ...item,
    goods_id: item.goods_id || item.id, // 如果 goods_id 不存在，使用 id
    num: Number(item.num) || 1,
    price: Number(item.price) || 0,
    checked: false,
  });

  //===================== 获取购物车数据==========================
  useEffect(() => {
    const fetchCartData = async () => {
      try {
        const { data } = await shopping({ uid: user?.data?.id });
        console.log("购物车原始数据:", data);

        if (data?.data?.list) {
          setCartItems(data.data.list.map(normalizeCartItem));
        }
      } catch (error) {
        console.error("获取购物车数据失败:", error);
      }
    };

    user?.data?.id && fetchCartData();
  }, [user?.data?.id]);

  // 获取推荐商品
  useEffect(() => {
    console.log("useEffect 触发");
    const fetchShopList = async () => {
      try {
        // 检查 user.data 是否存在
        if (!user?.data?.token || !user?.data?.id) {
          console.error("用户数据不存在或 token/id 为空");
          return;
        }

        // 发送请求
        const res = await home({
          headers: {
            token: user.data.token,
            id: user.data.id,
          },
        });
        console.log("请求结果:", res);

        // 检查返回数据
        if (res.data && Array.isArray(res.data.data.list)) {
          setShopList(res.data.data.list);
        } else {
          console.error("返回数据格式不符合预期:", res.data);
          setShopList([]);
        }
      } catch (error) {
        console.error("获取推荐商品失败:", error);
      }
    };

    user?.data?.id && fetchShopList();
  }, [user?.data?.id, user?.data?.token]);

  // 全选/取消全选
  const handleAllCheck = (checked: boolean) => {
    setCartItems((items) => items.map((item) => ({ ...item, checked })));
    setAllChecked(checked);
  };

  // 单个商品选中状态切换
  const handleItemCheck = (id: string, checked: boolean) => {
    const newItems = cartItems.map((item) =>
      item.id === id ? { ...item, checked } : item
    );
    setCartItems(newItems);
    setAllChecked(newItems.every((item) => item.checked));
  };

  // 自动计算全选状态
  useEffect(() => {
    setAllChecked(
      cartItems.length > 0 && cartItems.every((item) => item.checked)
    );
  }, [cartItems]);

  // 处理数量变化
  const handleQuantityChange = (id: string, type: "inc" | "dec") => {
    setCartItems((items) =>
      items.map((item) => {
        if (item.id === id) {
          const currentNum =
            typeof item.num === "string"
              ? parseInt(item.num, 10) || 1
              : item.num;

          const newNum =
            type === "inc" ? currentNum + 1 : Math.max(1, currentNum - 1);

          return { ...item, num: newNum };
        }
        return item;
      })
    );
  };

  // 计算总价
  const totalPrice = useMemo(() => {
    return cartItems.reduce((sum, item) => {
      const price =
        typeof item.price === "string"
          ? parseFloat(item.price) || 0
          : item.price;
      const num =
        typeof item.num === "string" ? parseInt(item.num, 10) || 0 : item.num;

      return item.checked ? sum + price * num : sum;
    }, 0);
  }, [cartItems]);

  // 结算处理
  const handleSettlement = () => {
    const selectedItems = cartItems
      .filter((item) => item.checked)
      .map((item) => ({
        ...item,
        num: Number(item.num) || 1,
        price: Number(item.price) || 0,
        goods_id: item.goods_id || item.id, // 再次确保 goods_id 存在
      }));

    if (selectedItems.length === 0) {
      alert("请先选择要结算的商品");
      return;
    }

    // 打印调试信息
    console.log("结算数据:", selectedItems);

    sessionStorage.setItem(
      "currentPurchase",
      JSON.stringify(
        selectedItems.map((item) => ({
          id: item.id,
          goods_id: item.goods_id,
          num: item.num,
          money: item.price,
        }))
      )
    );

    sessionStorage.setItem(
      "renderData",
      JSON.stringify(
        selectedItems.map((item) => ({
          id: item.id,
          goods_id: item.goods_id,
          num: item.num,
          money: item.price,
          name: item.title,
          img: item.img,
        }))
      )
    );

    navigate("/buynowS");
  };

  // 删除商品
  const handleDelete = async () => {
    const selectedIds = cartItems
      .filter((item) => item.checked)
      .map((item) => item.id)
      .join(",");

    if (!selectedIds) {
      alert("请选择要删除的商品");
      return;
    }

    try {
      await shopping_del({
        id: selectedIds,
        uid: user?.data?.id,
      });
      setCartItems((prev) => prev.filter((item) => !item.checked));
    } catch (error) {
      console.error("删除失败:", error);
    }
  };

  // 渲染购物车商品项
  const renderCartItem = (item: CartItem) => {
    const num =
      typeof item.num === "string" ? parseInt(item.num, 10) : item.num;
    const price =
      typeof item.price === "string" ? parseFloat(item.price) : item.price;

    return (
      <div className={shopcart.product} key={item.id}>
        <div className={shopcart.product_item}>
          <div className={shopcart.product_one}>
            <input
              type="checkbox"
              checked={item.checked}
              onChange={(e) => handleItemCheck(item.id, e.target.checked)}
              className={shopcart.oneCheck}
            />
            <img src={item.img} alt={item.title} />
          </div>
          <div className={shopcart.product_two}>
            <p>{item.title}</p>
            <span>{item.norm}</span>
            <div className={shopcart.ones}>
              <p className={shopcart.ppp}>￥{price.toFixed(2)}</p>
              <div className={shopcart.two}>
                <div onClick={() => handleQuantityChange(item.id, "dec")}>
                  <img src={Jian} alt="减少" />
                </div>
                <input
                  type="number"
                  value={num}
                  min="1"
                  readOnly
                  className={shopcart.quantityInput}
                />
                <div onClick={() => handleQuantityChange(item.id, "inc")}>
                  <img src={Jia} alt="增加" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className={shopcart.container}>
      <div className={shopcart.top}>购物车</div>

      <div className={shopcart.product_list}>
        {cartItems.length > 0 ? (
          cartItems.map(renderCartItem)
        ) : (
          <div className={shopcart.empty}>购物车是空的</div>
        )}
      </div>

      <div className={shopcart.three}>
        <div></div>
        <p>为您推荐</p>
        <div></div>
      </div>

      <div className={shopcart.recommend}>
        <div className={shopcart.shop}>
          {shopList.map((product) => (
            <div
              key={product.id}
              className={shopcart.shop_item}
              onClick={() => {
                localStorage.setItem("productId", product.id.toString());
                navigate("/detail");
              }}
            >
              <img
                src={product.img || "./img/head.jpg"}
                alt={product.title || "商品"}
              />
              <p>{product.title || "商品名称"}</p>
              <span>{product.synopsis || "商品描述"}</span>
              <div className={shopcart.items}>
                <p>￥{Number(product.price).toFixed(2)}</p>
                {product.original_price && (
                  <del>￥{Number(product.original_price).toFixed(2)}</del>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ height: "60px" }}></div>

      <div className={shopcart.xuan}>
        <div className={shopcart.xuans}>
          <input
            type="checkbox"
            checked={allChecked}
            onChange={(e) => handleAllCheck(e.target.checked)}
            className={shopcart.allCheck}
          />
          <p>全选</p>
        </div>
        <div className={shopcart.xuans_item}>
          合计:{" "}
          <span style={{ fontSize: "18px" }}>￥{totalPrice.toFixed(2)}</span>
        </div>
        <div onClick={handleSettlement} className={shopcart.xuan_one}>
          去结算({cartItems.filter((item) => item.checked).length})
        </div>
        <div onClick={handleDelete} className={shopcart.xuan_two}>
          删除
        </div>
      </div>

      <div className={shopcart.bottom}>
        {[
          { icon: navIcon1, text: "首页", path: "/home" },
          { icon: navIcon2, text: "分类", path: "/classify" },
          { icon: navIcon3, text: "打卡", path: "/clock", isPunch: true },
          { icon: navIcon4, text: "购物车", path: "/shopcart" },
          { icon: navIcon5, text: "我的", path: "/me" },
        ].map((nav, index) => (
          <div
            key={index}
            className={nav.isPunch ? shopcart.punch : shopcart.bottom_item}
            onClick={() => navigate(nav.path)}
          >
            <div>
              {nav.isPunch ? (
                <div className={shopcart.punches}>
                  <div className={shopcart.punchs}>
                    <img src={nav.icon} alt={nav.text} />
                  </div>
                </div>
              ) : (
                <img src={nav.icon} alt={nav.text} />
              )}
            </div>
            <p>{nav.text}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ShopCart;
